package com.sskj.ffex.v.activity;

import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.graphics.Rect;
import android.os.Build;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AlertDialog;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.TextView;

import com.bigkoo.pickerview.builder.TimePickerBuilder;
import com.bigkoo.pickerview.view.TimePickerView;
import com.bulong.rudeness.RudenessScreenHelper;
import com.shizhefei.mvc.MVCCoolHelper;
import com.shizhefei.view.coolrefreshview.CoolRefreshView;
import com.sskj.ffex.R;
import com.sskj.ffex.adapter.slimadapter.IViewInjector;
import com.sskj.ffex.adapter.slimadapter.SlimAdapter;
import com.sskj.ffex.adapter.slimadapter.SlimInjector;
import com.sskj.ffex.common.App;
import com.sskj.ffex.common.Constants;
import com.sskj.ffex.common.decoration.DividerLineItemDecoration;
import com.sskj.ffex.m.bean.FabiPublishListBean;
import com.sskj.ffex.mvchelper.ModelRx2DataSource;
import com.sskj.ffex.p.activity.FabiSellListPresenter;
import com.sskj.ffex.utils.ClickUtil;
import com.sskj.ffex.utils.TimeFormatUtil;
import com.sskj.ffex.v.base.BaseActivity;

import java.text.ParseException;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;

import butterknife.BindView;

public class FabiSellListActivity extends BaseActivity<FabiSellListPresenter> {

    @BindView(R.id.iv_back)
    ImageView ivBack;
    @BindView(R.id.tv_filter)
    TextView tvFilter;
    @BindView(R.id.recyclerView)
    RecyclerView recyclerView;
    @BindView(R.id.coolRefreshView)
    CoolRefreshView coolRefreshView;
    @BindView(R.id.ll_time)
    LinearLayout llTime;
    @BindView(R.id.tv_list_title)
    TextView tvTitle;
    private SlimAdapter<FabiPublishListBean> slimAdapter;
    private PopupWindow popupWindow;
    private boolean isStart = true;
    private TimePickerView startPicker;
    private TextView tvStartTime;
    private TextView tvEndTime;
    private View popupView;
    private boolean isBuy;
    private MVCCoolHelper<List<FabiPublishListBean>> mvcCoolHelper;
    private int curPos;
    private AlertDialog tipDialog;

    @Override
    protected int getLayoutResId() {
        return R.layout.activity_fabi_sell_list;
    }

    @Override
    public FabiSellListPresenter getPresenter() {
        return new FabiSellListPresenter();
    }

    @Override
    protected void initData() {


        HashMap<String, String> statusMap = new HashMap<>();
        HashMap<String, String> statusControlMap = new HashMap<>();
        statusMap.put("1", App.INSTANCE.getString(R.string.strFabiSellListActivity201));
        statusMap.put("2", App.INSTANCE.getString(R.string.strFabiSellListActivity203));
        statusMap.put("3", App.INSTANCE.getString(R.string.strFabiSellListActivity205));
        statusControlMap.put("1", App.INSTANCE.getString(R.string.strFabiSellListActivity207));
        statusControlMap.put("2", "");
        statusControlMap.put("3", "");
        isBuy = getIntent().getBooleanExtra(Constants.IS_BUY, true);
        tvTitle.setText(isBuy ? App.INSTANCE.getString(R.string.strFabiSellListActivity215) : App.INSTANCE.getString(R.string.strFabiSellListActivity216));
        ClickUtil.click(ivBack, this::finish);
        ClickUtil.click(300, tvFilter, this::showTimePop);
        recyclerView.setLayoutManager(new LinearLayoutManager(this));
        recyclerView.addItemDecoration(new DividerLineItemDecoration(this)
                .setFirstDraw(false)
                .setDividerColor(ContextCompat.getColor(this,R.color.divider))
                .setPaintWidth((int) RudenessScreenHelper.pt2px(this, 3)));
        slimAdapter = SlimAdapter.create().register(R.layout.recy_item_fabi_sell_list, new SlimInjector<FabiPublishListBean>() {
            @Override
            public void onInject(FabiPublishListBean data, IViewInjector injector) {

                injector.text(R.id.tv_id_code, data.getOrder_no())
                        .text(R.id.tv_status, statusMap.get(data.getStatus()))
                        .text(R.id.tv_detail, statusControlMap.get(data.getStatus()))
                        .text(R.id.tv_price, data.getPrice())
                        .text(R.id.tv_all_price, data.getTotalprice())
                        .text(R.id.tv_num, data.getTrans_num())
                        .text(R.id.tv_deal_num, data.getDeals_num())
                        .text(R.id.tv_time, data.getAdd_time())
                        .clicked(R.id.tv_detail, (v) -> {
                            curPos = slimAdapter.getData().indexOf(data);
                            if ("1".equals(data.getStatus())) {
                                showCancelTip();
                            }
                        });
            }
        }).attachTo(recyclerView).updateData(new ArrayList());
        ModelRx2DataSource<FabiPublishListBean> dataSource =
                new ModelRx2DataSource<>((ModelRx2DataSource.OnLoadSource<FabiPublishListBean>)
                        page -> mPresenter.getData(page, isBuy, tvStartTime == null ? "" : TimeFormatUtil.parseLongE(tvStartTime.getText().toString() + " 00:00:00"), tvEndTime == null ? "" : TimeFormatUtil.parseLongE(tvEndTime.getText().toString() + " 23:59:59")), 10);
        mvcCoolHelper = new MVCCoolHelper<>(coolRefreshView);
        mvcCoolHelper.setDataSource(dataSource);
        mvcCoolHelper.setAdapter(slimAdapter);
        mvcCoolHelper.refresh();
    }

    /**
     * 显示撤单提示
     */
    private void showCancelTip() {
        if (tipDialog == null) {
            tipDialog = new AlertDialog.Builder(this)
                    .setTitle(App.INSTANCE.getString(R.string.strFabiSellListActivity223))
                    .setMessage(App.INSTANCE.getString(R.string.strFabiSellListActivity224))
                    .setPositiveButton(App.INSTANCE.getString(R.string.strFabiSellListActivity225), (dialog, which) -> {
                        dialog.dismiss();
                        mPresenter.cancelOrder(isBuy, slimAdapter.getDataItem(curPos).getId());
                    })
                    .setNegativeButton(App.INSTANCE.getString(R.string.strFabiSellListActivity226), (dialog, which) -> dialog.dismiss()).create();
        }
        tipDialog.show();
    }

    /**
     * 显示时间选择弹窗
     */
    private void showTimePop() {
        if (popupWindow != null && popupWindow.isShowing()) {
            popupWindow.dismiss();
        } else {
            popupView = LayoutInflater.from(this).inflate(R.layout.popup_fabi_time_select, null);
            tvStartTime = popupView.findViewById(R.id.tv_start_time);
            tvEndTime = popupView.findViewById(R.id.tv_end_time);
            ClickUtil.click(popupView.findViewById(R.id.tv_apply), () -> {
                popupWindow.dismiss();
                mvcCoolHelper.refresh();
            });
            ClickUtil.click(popupView.findViewById(R.id.tv_cancel), () -> {
                tvStartTime.setText("");
                tvEndTime.setText("");
            });
            initTime();
            View view = popupView.findViewById(R.id.view);
            ClickUtil.click(view, () -> {
                popupWindow.dismiss();
            });

            popupWindow = new PopupWindow(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT);
            popupWindow.setContentView(popupView);
//          popupWindow.setBackgroundDrawable(new ColorDrawable(0x00000000));
//          popupWindow.setOutsideTouchable(true);
//          popupWindow.setAnimationStyle(R.style.AnimDown);
//          popupWindow.setClippingEnabled(true);
            if (Build.VERSION.SDK_INT > 24) {
                Rect rect = new Rect();
                llTime.getGlobalVisibleRect(rect);
                int h = llTime.getResources().getDisplayMetrics().heightPixels - rect.bottom;
                popupWindow.setHeight(h);
            }
            popupWindow.showAsDropDown(llTime);
        }


    }

    private void initTime() {
        Calendar instance = Calendar.getInstance();
        instance.add(Calendar.DAY_OF_YEAR, -7);
        tvStartTime.setText(TimeFormatUtil.SF_FORMAT_B.format(instance.getTime()));
        tvEndTime.setText(TimeFormatUtil.SF_FORMAT_B.format(Calendar.getInstance().getTime()));
        ClickUtil.click(tvStartTime, () -> showTime(true));
        ClickUtil.click(tvEndTime, () -> showTime(false));
    }


    private void showTime(boolean isStart) {
        this.isStart = isStart;
        startPicker = new TimePickerBuilder(this, (date, v) -> {
            if (this.isStart) {
                tvStartTime.setText(TimeFormatUtil.limitMaxDate(date));
            } else {
                tvEndTime.setText(TimeFormatUtil.limitMaxDate(date));
            }
        }).setDecorView((ViewGroup) popupView).build();
        try {
            Date parse = TimeFormatUtil.SF_FORMAT_B.parse(isStart ? tvStartTime.getText().toString() : tvEndTime.getText().toString());
            Calendar instance = Calendar.getInstance();
            instance.setTime(parse);
            startPicker.setDate(instance);
            startPicker.show();
        } catch (ParseException e) {
            startPicker.show();

        }
    }

    public static void start(Context context, boolean isBuy) {
        Intent starter = new Intent(context, FabiSellListActivity.class);
        starter.putExtra(Constants.IS_BUY, isBuy);
        context.startActivity(starter);
    }

    public void refresh() {
        mvcCoolHelper.refresh();
    }

    public void delete() {
        slimAdapter.getData().remove(curPos);
        slimAdapter.notifyItemRemoved(curPos);
    }
}
